/**
 * 
 */
package org.william.common_boot.database;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.After;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Before;  
import org.aspectj.lang.annotation.Pointcut;  
import org.aspectj.lang.reflect.MethodSignature;  
import org.springframework.core.annotation.Order;  
import org.springframework.stereotype.Component;  
/** 
 * Description: 
 * @author xuhongwei
 * @version 1.0
 * <pre>
 * Modification History: 
 * Date         Author      Version     Description 
------------------------------------------------------------------
 * 2018年4月12日    xuhongwei     1.0        1.0 Version 
 * </pre>
 */
@Aspect
@Order(-1) //保证该AOP在@Transactional之前执行  
@Component
public class DynamicDataSourceAspect {

//	@Pointcut("execution(* org.william.common_boot.business.service..*.*(..))")  
	@Pointcut("execution(* org.william.common_boot.*.service..*.*(..))")  
    public void pointCut() {  
		
    }  
  
	/***
	 * 
	 * 
	 * Description: 
	 * @param
	 * @return Object
	 * @throws
	 * @Author xuhongwei
	 * Create Date: 2018年4月12日
	 */
	@Before("pointCut()")
	public void changeDataSource(JoinPoint joinPoint){
		
		String sourceName=null;
		
		 //获得当前访问的class  
		Class<?> classes=joinPoint.getTarget().getClass();
		
		//获得访问的方法名称  
		String methodName=joinPoint.getSignature().getName();
		
	    Method abstractMethod = ((MethodSignature) joinPoint.getSignature()).getMethod();  
		
		if (abstractMethod.isAnnotationPresent(DBSource.class)) {  
            sourceName = abstractMethod.getAnnotation(DBSource.class).name();  
        }  
		
		//接口方法参数类型  
        Class<?>[] parameterTypes = abstractMethod.getParameterTypes();  
        
        try {  
            //实现类中的该方法  
            Method method = classes.getMethod(methodName, parameterTypes);  
            if (method.isAnnotationPresent(DBSource.class)) {  
                sourceName = method.getAnnotation(DBSource.class).name();  
                
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if (sourceName != null) {
        	System.out.println("动态切换数据源：------ " + sourceName);  
            DynamicDataSource.setDataSource(sourceName);  
        }  
        
	}
	
  
    @After("pointCut()")  
    public void after(JoinPoint point) {  
        DynamicDataSource.cleanDataSource();
    } 
	
}	
